<template>
	<el-form style="width: 100%;">
		<el-row :gutter="12">
			<el-col :span="6">
				<el-form-item>
					<el-select v-model="areaId1" placeholder="省" @change="hasAreaId1">
						<el-option v-for="item in areaList1" :key="item.id" :value="item.id"
							:label="item.areaName"></el-option>
					</el-select>
				</el-form-item>
			</el-col>
			<el-col :span="6">
				<el-form-item>
					<el-select v-model="areaId2" placeholder="市" @change="hasAreaId2">
						<el-option v-for="item in areaList2" :key="item.id" :value="item.id"
							:label="item.areaName"></el-option>
					</el-select>
				</el-form-item>
			</el-col>
			<el-col :span="6">
				<el-form-item>
					<el-select v-model="areaId3" placeholder="区" @change="hasAreaId3">
						<el-option v-for="item in areaList3" :key="item.id" :value="item.id"
							:label="item.areaName"></el-option>
					</el-select>
				</el-form-item>
			</el-col>
		</el-row>

	</el-form>
</template>

<script setup lang="ts">
import { AreaItem, getAreaByParentIdApi } from '@renderer/api/area';
import { onMounted, ref, watch } from 'vue';

const props = defineProps<{
	dialogVisible: boolean
	province: string
	city: string
	county: string
}>()
const emits = defineEmits(['addSuccess'])

const areaId1 = ref('')
const areaId2 = ref('')
const areaId3 = ref('')
const areaList1 = ref<AreaItem[]>([])
const areaList2 = ref<AreaItem[]>([])
const areaList3 = ref<AreaItem[]>([])

// 获取地区的方法
const getAreaByParentIdData = async (parentId: string) => {
	const { code, data } = await getAreaByParentIdApi({ parentId })
	if (code !== '200') return

	return data
}
const hasAreaId1 = async (id: string) => {
	areaId1.value = id
	areaList2.value = await getAreaByParentIdData(id) as AreaItem[]
}
const hasAreaId2 = async (id: string) => {
	areaId2.value = id
	areaList3.value = await getAreaByParentIdData(id) as AreaItem[]
}
const hasAreaId3 = async (id: string) => {
	areaId3.value = id
	emits('addSuccess', [areaId1, areaId2, areaId3])
}

watch(() => props.county, async () => {
	if (props.county) {
		areaId1.value = props.province
		areaId2.value = props.city
		areaId3.value = props.county

		hasAreaId1(areaId1.value)
		props.city && hasAreaId2(areaId2.value)
	} else {
		areaId1.value = ''
		areaId2.value = ''
		areaId3.value = ''
	}
})
onMounted(async () => {
	areaList1.value = await getAreaByParentIdData('1') as AreaItem[]
})
</script>

<style scoped></style>